package com.ericzong.util.file.xml;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.jdom2.Document;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;

public class JDomUtils
{
	/**
	 * 保存 xml 文档
	 * 
	 * @param document
	 *            要保存的 Document 对象
	 * @param fileName
	 *            文件路径
	 * @throws IOException
	 */
	public static void save( Document document, String fileName ) throws IOException
	{
		Format format = Format.getPrettyFormat();
		format.setExpandEmptyElements( true );
		// format.setOmitDeclaration(true);
		// format.setOmitEncoding(true);
		// format.setLineSeparator("\r\n");

		XMLOutputter outputter = new XMLOutputter( format );
		// outputter.setFormat(format);
		outputter.output( document, new FileOutputStream( fileName ) );
	}

	public static Document read( String fileName ) throws FileNotFoundException, JDOMException,
			IOException
	{
		SAXBuilder builder = new SAXBuilder();
		Document document = builder.build( new FileInputStream( fileName ) );
		return document;
	}
}
